package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>implements CategoryService {

    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;
    @Override
    public void deleteById(Long id) {
//        自己业务方法，实现逻辑
//        先检查当前分类中，是否有菜品，或套餐，需要什么？
//        方案：
//        需要菜品的业务方法，根据分类ID查询是否有菜品
//        构建菜品查询的条件，进行业务查询
        LambdaQueryWrapper<Dish> queryWrapperDish = new LambdaQueryWrapper<>();
        queryWrapperDish.eq(Dish::getCategoryId,id);
        int countDish = dishService.count(queryWrapperDish);
        log.info("[删除分类-分类查询菜品]，countDish:{}",countDish);
        if (countDish > 0){
            //不能删除
            log.info("[删除分类-分类查询菜品]，有关联数据，不能删除");
//            业务异常，根据业务自己抛出异常
//            throw new RuntimeException("菜品有关联数据，不能删除");
            throw new CustomException("菜品有关联数据，不能删除");
        }
//        需要套餐业务方法，根据分类查询是否有套餐
        LambdaQueryWrapper<Setmeal> queryWrapperSetmeal = new LambdaQueryWrapper<>();
        queryWrapperSetmeal.eq(Setmeal::getCategoryId,id);
        int countSetmeal = setmealService.count(queryWrapperSetmeal);
        log.info("[删除分类-分类查询套餐]，countSetmeal:{}",countSetmeal);
        if (countSetmeal > 0){
            log.info("[删除分类-分类查询套餐]，有关联数据，不能删除");
            throw new CustomException("套餐有关联数据，不能删除");
        }
        //如果没有关联数据，能删
        this.removeById(id);   //this当前对象，super,父类引用
    }
}
